from django.core.paginator import PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from pure_pagination import Paginator

from course.models import Course
from operation.models import UserFavorite
from organization.forms import UserAskForm
from organization.models import CourseOrg, CityDict, Teacher
from users.models import UserProfile


class OrgView(View):
    ''' 课程机构首页 '''
    def get(self, request):
        # 获取全部课程机构和总数
        all_orgs = CourseOrg.objects.all()
        org_onums = all_orgs.count()
        # 获取全部城市
        all_citys = CityDict.objects.all()
        # 热门机构
        hot_orgs = all_orgs.order_by('-click_nums')[:3]
        # 机构全局搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_orgs = all_orgs.filter(Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords))
        # 根据条件筛选
        city_id = request.GET.get('city','')
        if city_id:
            all_orgs = all_orgs.filter(city_id=int(city_id))
        category = request.GET.get('ct','')
        if category:
            all_orgs = all_orgs.filter(category=category)
        sort = request.GET.get('sort','')
        if sort:
            if sort == 'students':
                all_orgs = all_orgs.order_by('-students')
            elif sort == 'courses':
                all_orgs = all_orgs.order_by("-course_nums")

        # 数据分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_orgs, 4, request=request)
        orgs = p.page(page)
        # print(orgs.pages)
        return render(request, 'org-list.html', {'all_orgs': orgs,
                                                 'org_nums': org_onums,
                                                 'all_citys': all_citys,
                                                 'city_id': city_id,
                                                 'category': category,
                                                 'hot_orgs': hot_orgs,
                                                 'sort': sort})


class AddUserAskView(View):
    '''
    用户咨询
    '''
    def post(self, request):
        userask_form = UserAskForm(request.POST)
        print(userask_form.is_valid())
        if userask_form.is_valid():
            user_ask = userask_form.save(commit=True)
            # 如果保存成功,返回json字符串,后面content type是告诉浏览器返回的数据类型
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            # 如果保存失败，返回json字符串,并将form的报错信息通过msg传递到前端
            return HttpResponse('{"status":"fail","msg":"添加出错"}', content_type='application/json')


# 机构详情
class OrgHomeView(View):
    def get(self, request, org_id):
        current_page = 'home'
        # 根据id查找课程机构
        course_org = CourseOrg.objects.get(id=int(org_id))
        course_org.click_nums += 1
        course_org.save()
        # 反向查询机构所有的课程和教师
        all_courses = course_org.course_set.all()[:4]
        all_teacher = course_org.teacher_set.all()[:2]
        # 判断用户收藏
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        return render(request, 'org-detail-homepage.html', {
            'current_page': current_page,
            'course_org': course_org,
            'all_courses': all_courses,
            'all_teacher': all_teacher,
            'has_fav': has_fav,
        })


# 机构课程列表
class OrgCourseView(View):
    def get(self,request, org_id):
        current_page = 'course'
        # 根据id查询机构
        course_org = CourseOrg.objects.get(id=int(org_id))
        # 通过机构查找课程，内建变量，找到指向这个字段的外键引用
        all_courses = course_org.course_set.all()
        # 查询用户收藏
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        return render(request, 'org-detail-course.html', {
            'current_page': current_page,
            'course_org': course_org,
            'all_courses': all_courses,
            'has_fav': has_fav,
        })


# 机构详情
class OrgDescView(View):
    def get(self, request, org_id):
        current_page = 'desc'
        course_org = CourseOrg.objects.get(id=org_id)
        # 判断用户收藏
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True
        return render(request, 'org-detail-desc.html', {
            'current_page': current_page,
            'course_org': course_org,
            'has_fav': has_fav
        })


# 机构教师列表
class OrgTeacherView(View):
    def get(self, request, org_id):
        current_page = 'teacher'
        course_org = CourseOrg.objects.get(id=int(org_id))
        all_teacher = course_org.teacher_set.all()
        # 判断用户收藏
        has_fav = False
        if request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):
                has_fav = True

        return render(request, 'org-detail-teachers.html', {
            'current_page': current_page,
            'course_org': course_org,
            'all_teacher': all_teacher,
            'has_fav': has_fav,
        })


class AddFavView(View):
    '''
    用户收藏和取消收藏
    '''
    def post(self, request):
        id = request.POST.get('fav_id', 0)      # 防止后边int(fav_id)时出错
        type = request.POST.get('fav_type', 0)  # 防止int(fav_type)出错

        if not request.user.is_authenticated:
            # 检查用户登录状态，未登录返回fail
            return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type="application/json")
        exist_record = UserFavorite.objects.filter(user=request.user, fav_id=int(id), fav_type=int(type))
        if exist_record:
            '''查询记录是否存在，如果存在执行取消收藏操作'''
            exist_record.delete()
            if int(type) == 1:
                course = Course.objects.get(id=int(id))
                course.fav_nums -= 1
                if course.fav_nums < 0:
                    course.fav_nums = 0
                course.save()
            elif int(type) == 2:
                org = CourseOrg.objects.get(id=int(id))
                org.fav_nums -= 1
                if org.fav_nums < 0:
                    org.fav_nums = 0
                org.save()
            elif int(type) == 3:
                teacher = Teacher.objects.get(id=int(id))
                teacher.fav_nums -= 1
                if teacher.fav_nums < 0:
                    teacher.fav_nums = 0
                teacher.save()
            return HttpResponse('{"status":"success", "msg":"收藏"}', content_type='application/json')
        else:
            user_fav = UserFavorite()
            if int(id)>0 and int(type)>0:
                user_fav.user = request.user
                user_fav.fav_id = int(id)
                user_fav.fav_type = int(type)
                user_fav.save()
                if int(type) == 1:
                    course = Course.objects.get(id=int(id))
                    course.fav_nums += 1
                    course.save()
                elif int(type) == 2:
                    org = CourseOrg.objects.get(id=int(id))
                    org.fav_nums += 1
                    org.save()
                elif int(type) == 3:
                    teacher = Teacher.objects.get(id=int(id))
                    teacher.fav_nums += 1
                    teacher.save()
                return HttpResponse('{"status":"success", "msg":"已收藏"}', content_type='application/json')
            else:
                return HttpResponse('{"status":"fail", "msg":"收藏出错"}', content_type='application/json')


class TeacherListView(View):
    '''讲师列表'''
    def get(self, request):
        all_teachers = Teacher.objects.all()
        # 讲师总数
        teacher_nums = all_teachers.count()
        # 排序
        sort = request.GET.get('sort', '')
        if sort:
            if sort == 'hot':
                all_teachers = all_teachers.order_by('-click_nums')
        # 讲师全局搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_teachers = all_teachers.filter(Q(name__icontains=search_keywords))
        # 讲师排行
        sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]
        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_teachers, 5, request=request)
        teachers = p.page(page)
        return render(request, 'teachers-list.html', {
            'all_teachers': teachers,
            'teacher_nums': teacher_nums,
            'sorted_teacher': sorted_teacher,
            'sort': sort
        })


class TeacherDetailView(View):
    '''讲师详情'''
    def get(self, request, teacher_id):
        teacher = Teacher.objects.get(id=int(teacher_id))
        teacher.click_nums += 1
        teacher.save()
        all_course = Course.objects.filter(teacher=teacher)
        # 讲师排行
        sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]
        # 讲师收藏和机构收藏
        has_teacher_faved = False
        if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id=teacher.id):
            has_teacher_faved = True
        has_org_faved = False
        if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org_id):
            has_org_faved = True
        return render(request, 'teacher-detail.html', {
            'teacher': teacher,
            'all_courses': all_course,
            'sorted_teacher': sorted_teacher,
            'has_teacher_faved': has_teacher_faved,
            'has_org_faved': has_org_faved
        })